<template>
  <div class="menu-list" v-if="itemList.length !== 0" ref="menuListRef" @scroll="handleScroll">
    <div v-for="item in visibleItems" :key="item.id" class="menu-item" :style="{ height: itemHeight + 'px' }">
      <div class="image"><img :src="item.image" /></div>
      <div class="info" @click="openPopup(item.id)">
        <h3 class="name">{{ item.name }}</h3>
        <p class="description">{{ item.description }}</p>
        <p class="price"><i>￥</i>{{ item.price }}</p>
      </div>
      <div class="btn" style="display: flex; align-items: center">
        <button v-if="item.flavors && item.flavors?.length !== 0" class="select-btn" @click="openFlavorPopup(item.id)">
          选规格
        </button>
        <div class="add-btn" v-else>
          <van-icon name="plus" color="#fff" @click="addCart(item)" />
        </div>
      </div>
      <!-- 占位符 -->
      <div class="placeholder" :style="{ height: placeholderHeight + 'px' }"></div>
      <!-- 选择口味弹窗 -->
      <menu-flavors v-model:flavor-popup="flavorPopups[item.id]" :item="item" @add-cart="addCart"/>
      <!-- <van-popup v-model:show="flavorPopup" round @click-overlay="onClickOverlay">
        <div style="height: 46px; line-height: 46px; text-align: center; background-color: #f5f5f5">
          {{ item.name }}
        </div>
        <div v-for="it in item.flavors" :key="it.id"
          style="flex: 1; overflow-y: auto; padding: 20px 10px; min-height: 120px">
          <h3>{{ it.name }}</h3>
          <div class="flavor-list">
            <div v-for="i in JSON.parse(it.value)" :key="i" :class="{ select: dishFlover === i }" class="flavor-item">
              <span @click="selectFlavor(i)">{{ i }}</span>
            </div>
          </div>
        </div>
        <div class="flavor-bottom">
          <span>
            已选规格:<span style="color: #ff0000; padding-left: 5px">{{ dishFlover }} </span></span>
          <button @click="addCart(item)" :class="dishFlover === '' ? 'disable-btn' : 'add-cart'">加入购物车</button>
        </div>
      </van-popup> -->
    </div>
    <div class="load-complete flex" 已经到底啦></div>
  </div>
  <star-empty v-else />
  <!-- 菜品详细信息弹窗 -->
  <menu-info :item-info="dishInfo" :comment-list="commentList" :is-popup-visible="dishPopup"
    :show-select-btn="dishInfo.flavors && dishInfo.flavors?.length !== 0" @open-flavorpopup="openFlavorPopup"
    @close-popup="closePopup" @add-cart="addCart" />
</template>
<script setup lang="ts">
import menuInfo from './menu-info.vue'
import menuFlavors from './menu-flavors.vue'
import type { DishItemResult } from '@/types/meal'
import type { BusinessItemResult } from '@/types/business'
import { addCartAPI } from '@/api/cart'
import { computed, onMounted, ref } from 'vue'
import { getDishByIdAPI } from '@/api/meal'
import type { CommentItem } from '@/types/comment'
import * as commentAPI from '@/api/comment'
const props = defineProps<{
  itemList: DishItemResult[]
  business: BusinessItemResult
  itemHeight: number
  startIndex: number
  endIndex: number
  visibleCount: number
}>()
const emits = defineEmits<{
  (e: 'getCartList', businessId: number): void
  (e: 'change-start', value: number): void
  (e: 'change-end', value: number): void
}>()

// 口味弹窗
const flavorPopups = ref<Record<number, boolean>>({});

// 打开特定菜品的弹窗
const openFlavorPopup = (dishId: number) => {
  flavorPopups.value[dishId] = true;
};

// 添加购物车
const addCart = async (item: DishItemResult, dishFlavor?: string) => {
  console.log(dishFlavor);

  const params = {
    dishId: item.id,
    businessId: props.business.id,
    dishFlavor: dishFlavor,
  }
  try {
    if (item.flavors.length !== 0 && !flavorPopups.value[item.id]) return
    // console.log(dishFlover.value)
    await addCartAPI(params)
    flavorPopups.value[item.id] = false
    if (dishPopup.value) closePopup()
    emits('getCartList', props.business.id)
  } catch (error) {
    console.log(error)
  }
}
// 评论列表
const commentList = ref<CommentItem[]>([])

// 获取评论列表
const getDishCommentList = async (dishId: number) => {
  try {
    const res = await commentAPI.getCommentListAPI({
      pageQueryDTO: {
        page: 1,
        pageSize: 10,
      },
      dishId,
    }) // 请根据实际情况传递参数
    commentList.value = res.data.records // 请根据实际返回数据结构修改
  } catch (error) {
    console.error('获取评论列表失败', error)
  }
}
// 菜品弹窗
const dishPopup = ref(false)
const dishInfo = ref({} as DishItemResult)
const openPopup = async (id: number) => {
  dishPopup.value = true
  try {
    const { data } = await getDishByIdAPI(id)
    dishInfo.value = data
    getDishCommentList(id)
  } catch (error) {
    console.log(error)
  }
}
// 关闭菜品弹窗
const closePopup = () => {
  dishPopup.value = false
}
// dom实例 监听滚动
const menuListRef = ref<HTMLElement | null>(null)

const visibleItems = computed(() => {
  return props.itemList.slice(0, props.visibleCount) // 截取数组
})
const placeholderHeight = computed(() => {
  const totalHeight = props.itemList.length * props.itemHeight
  const visibleHeight = props.visibleCount * props.itemHeight
  return totalHeight - visibleHeight
})
const handleScroll = () => {
  if (menuListRef.value) {
    // 获取滚动容器的滚动位置
    const scrollTop = menuListRef.value.scrollTop
    emits('change-start', Math.floor(scrollTop / props.itemHeight))
    emits('change-end', props.startIndex + props.visibleCount)
    if (props.endIndex > props.itemList.length) {
      emits('change-end', props.itemList.length)
    }
  }
}
onMounted(() => {
  handleScroll()
})
import './menu.scss'
import { add } from 'lodash'
</script>
<style lang="scss" scoped>
:deep() {
  .van-nav-bar__arrow {
    height: 25px;
    width: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: #000;
    opacity: 0.6;
    color: #fff;
  }
}

.menu-list {
  // height: 400px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.van-popup {
  min-width: 90%;
  box-sizing: border-box;
}

.dish-popup {
  height: 100%;
  min-width: 100%;
  box-sizing: border-box;
}

.dish-info {
  background: #fff;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.evaluate {
  margin-top: 10px;
  border-radius: 5px 5px 0 0;
  background: var(--gray-background);
}

.placeholder {
  position: absolute;
  /* 绝对定位 */
  bottom: 0;
  /* 定位到底部 */
  left: 0;
  /* 定位到左侧 */
  right: 0;
  /* 定位到右侧 */
  pointer-events: none;
  /* 确保占位符不会影响滚动行为 */
}
</style>
